<?php
class Pageley_Domain_EntityComparator implements Pageley_Util_Comparator {
    
    private $order;
    
    public function __construct($order) {
        $this->order = $order;
    }
    
    public function compare($entity1, $entity2) {
        $result = 0;
        foreach($this->order as $propertyName => $direction) {
            $value1 = $entity1->get($propertyName);
            $value2 = $entity2->get($propertyName);
            $result = $this->compareProperty($value1, $value2);
            if($result != 0) {
                if(!$direction->isAscending()) {
                    $result = -$result;
                }
                break;
            }
        }
        return $result;
        
    }
    
    private function compareProperty($value1, $value2) {
        $result = 0;
        if($value1 != null && $value2 != null) { 
            if(is_object($value1) && $value1 instanceof Pageley_Util_Comparable) {
                $result = $value1->compareTo($value2);
            } else if(!is_object($value1)) {
                $result = $value1 > $value2 ? 1 : 
                    ($value1 == $value2 ? 0 : -1);
            }
        } else if($value1 !== null) {
            $result = 1;
        } else if($value2 !== null) {
            $result = -1;
        }
        return $result;
    }
}